package com.zllkj.mm.module.main.fragments;

import android.Manifest;
import android.database.DatabaseUtils;
import android.graphics.BitmapFactory;
import android.icu.util.ULocale;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.baidu.location.LocationClient;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zllkj.mm.R;
import com.zllkj.mm.api.network.RetrofitHelper;
import com.zllkj.mm.api.network.RxHelper;
import com.zllkj.mm.api.network.subscriber.BaseRxSubscriber;
import com.zllkj.mm.api.network.subscriber.BaseString;
import com.zllkj.mm.base.BaseTitleFragment;
import com.zllkj.mm.common.ClientConfig;
import com.zllkj.mm.common.L;
import com.zllkj.mm.model.entity.FactoryStations;
import com.zllkj.mm.model.entity.HomeShopListS;
import com.zllkj.mm.model.entity.UserSelfVo;
import com.zllkj.mm.module.goods.NearByGoodsListFragment;
import com.zllkj.mm.module.goods.NearByGoodsListItemFragment;
import com.zllkj.mm.module.home.fragments.SquareFragment;
import com.zllkj.mm.module.moment.FriendListFragment;
import com.zllkj.mm.util.EmptyUtils;
import com.zllkj.mm.util.common.AppUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页
 */
public class MainFragment extends BaseTitleFragment {

    @BindView(R.id.map)
    MapView mMapView;

    private View mapLayout;

    private AMap aMap;

    //声明mlocationClient对象
    public LocationClient mLocationClient = null;

    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    @BindView(R.id.moreIv)
    ImageView moreIv;

    @BindView(R.id.moreCategoryLayout)
    LinearLayout moreCategoryLayout;

    @BindView(R.id.freetimeLayout)
    LinearLayout freeTimeLayout;


    @BindView(R.id.locationTv)
    TextView locationTv;

    double lat = -1.0;
    double lon = -1.0;

    ArrayList<Marker> markersList = new ArrayList<>();

    Marker currentMarker;



    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_main;
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        final RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(isGranted -> {
                    if (isGranted) {
                        getLocation();
                    } else {

                    }
                });

    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        hideTitle();
        moreCategoryLayout.setVisibility(View.VISIBLE);

    }



    public void getLocation() {
        //定位蓝点
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//定位一次   //LOCATION_TYPE_LOCATE且将视角移动到地图中心点。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {

                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()),18));
                HashMap map = new HashMap();
                map.put("currentPage", "1");
                map.put("latitude", location.getLatitude());
                map.put("longitude", location.getLongitude());
                map.put("pageSize", "20");
                //搜索内容
                map.put("searchContent", "");

                lat = location.getLatitude();
                lon = location.getLongitude();

                AppUtils.lat = lat;
                AppUtils.lng = lon;


                addSubscribe(RetrofitHelper.getInstance().getApi()
                                .shopList(map)
                                .compose(RxHelper.<List<FactoryStations>>defaultHandleResult())
                                .subscribe(new BaseRxSubscriber<HomeShopListS>() {
                                               @Override
                                               protected void onSucc(HomeShopListS o) {
//                                                       //白云山风景名胜区
//                                                       o.get(0).latitude = 23.180189;
//                                                       o.get(0).longitude = 113.297117;

                                                   markersList.clear();
                                                   HomeShopListS.ShopIndexVo factoryStations_min = null;//最短距离的一个
                                                   float minLen = 0;//最短距离
                                                   for (HomeShopListS.ShopIndexVo factoryStations : o.records) {
                                                       MarkerOptions markerOptions = new MarkerOptions();
                                                       markerOptions.position(new LatLng(Double.parseDouble(factoryStations.latitude), Double.parseDouble(factoryStations.longitude)));
                                                       //markerOptions.title(factoryStations.shopName).snippet(factoryStations.address);
                                                       markerOptions.title(factoryStations.shopName);
                                                       markerOptions.draggable(false);//设置Marker可拖动
                                                       markerOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                                               .decodeResource(getResources(), R.mipmap.ic_back_add)));
                                                       final Marker marker = aMap.addMarker(markerOptions);

                                                       //绘制动画效果 Marker
                                                       Animation animation = new ScaleAnimation(0, 1, 0, 1);
                                                       long duration = 1000L;
                                                       animation.setDuration(duration);
                                                       animation.setInterpolator(new LinearInterpolator());
                                                       marker.setAnimation(animation);
                                                       marker.startAnimation();
                                                       marker.setObject(factoryStations.id);
                                                       markersList.add(marker);
//                                           marker.setInfoWindowEnable(false);//先不要InfoWindow,或setOnMarkerClickListener返回否则返回false

                                                       // 定义 Marker 点击事件监听
                                                       // 绑定 Marker 被点击事件
                                                       // marker 对象被点击时回调的接口
                                                       // 返回 true 则表示接口已响应事件，否则返回false
                                                       aMap.setOnMarkerClickListener(marker1 -> {//经调试，marker1不再相等旧的
                                                           currentMarker = marker1;
                                                           //   rlInfo.setVisibility(View.VISIBLE);
                                                           // tvTitle.setText(marker1.getTitle());
                                                           //   tvAddress.setText(marker1.getSnippet());
                                                           // AnimationUtil.startTransYAnimation(llInfo2, 500, 0, 200);
                                                           for (Marker marker2 : markersList) {
                                                               marker2.setMarkerOptions(marker2.getOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                                                       .decodeResource(getResources(), R.mipmap.ic_back_add))));
                                                           }
//                                                               currentMarker.setMarkerOptions(currentMarker.getOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
//                                                                       .decodeResource(getResources(), R.mipmap.logo_map2))));
                                                           return true;
                                                       });

                                                       //找出距离短的那个
                                                       if (null == factoryStations_min) {
                                                           factoryStations_min = factoryStations;
                                                       }
                                                       LatLng start = new LatLng(Double.parseDouble(factoryStations_min.latitude), Double.parseDouble(factoryStations_min.longitude));
                                                       LatLng end = new LatLng(Double.parseDouble(factoryStations.latitude), Double.parseDouble(factoryStations.longitude));
                                                       float v = AMapUtils.calculateLineDistance(start, end);
                                                       if (minLen == 0) {
                                                           minLen = v;
                                                       }
                                                       if (v < minLen) {
                                                           minLen = v;
                                                           factoryStations_min = factoryStations;
                                                       }
                                                   }

                                                   //显示范围
                                                   LatLngBounds.Builder builder = new LatLngBounds.Builder();
                                                   LatLngBounds bounds = null;
                                                   builder.include(new LatLng(location.getLatitude(), location.getLongitude()));//当前
                                                   builder.include(new LatLng(Double.parseDouble(factoryStations_min.latitude), Double.parseDouble(factoryStations_min.longitude)));
                                                   bounds = builder.build();
                                                   aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 200));

                                               }
                                           }
                                )
                );
            }
        });

        RetrofitHelper.getInstance().getApi()
                .fileGetBaseUrl(L.sign(new HashMap() {{
                }}))
                .compose(RxHelper.<BaseString>defaultHandleResult())
                .subscribe(new BaseRxSubscriber<BaseString>() {
                    @Override
                    protected void onSucc(BaseString o) {
                        ClientConfig.IMG_URL = o.string;
                    }
                })
        ;

        RetrofitHelper.getInstance().getApi()
                .getUserInfo(L.sign(L.sign(new HashMap())))
                .compose(RxHelper.<UserSelfVo>defaultHandleResult())
                .subscribe(new BaseRxSubscriber<UserSelfVo>() {
                    @Override
                    protected void onSucc(UserSelfVo userSelfVo) {
                        Hawk.put(L.userInfo,userSelfVo);


                    }
                })
        ;
    }


    @OnClick({R.id.moreIv,R.id.everyOneBossLayout,R.id.freetimeLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.moreIv:
                if (moreCategoryLayout.getVisibility() == View.VISIBLE) {
                    moreCategoryLayout.setVisibility(View.GONE);
                } else {
                    moreIv.setImageResource(R.mipmap.ic_more);
                    moreCategoryLayout.setVisibility(View.VISIBLE);

                }
                break;
            case R.id.everyOneBossLayout:
                addFragment(new NearByGoodsListFragment());
                break;
            case R.id.freetimeLayout:
                addFragment(new SquareFragment(SquareFragment.Companion.getFRIEND_DATA_TYPE_ONLY_FREE_TIME()));
                break;

        }
    }


    @Override
    public void onResume() {
        Log.i("sys", "mf onResume");
        super.onResume();
        mMapView.onResume();
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
//           mMapView.onDestroy();
    }

}
